package com.example.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.common.ARouterPath
import com.example.mvi_core.model.BaseActivity
import com.example.user.databinding.ActivityUserBinding
import com.example.user.intent.UserIntent
import com.example.user.state.UserState
import com.example.user.viewmodel.UserViewModel
import com.google.android.material.textfield.TextInputEditText
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
@Route(path = ARouterPath.USER_JUMP_REGISTER)
class UserActivity : BaseActivity() {
    private var user: TextInputEditText?=null
    private var pas:TextInputEditText?=null
    private var register:Button?=null
    private val viewModel by lazy{UserViewModel()}
    override fun getLayoutRootView(): View? {
        return null
    }

    override fun getLayoutId(layout: Int): Int {
        return R.layout.activity_user
    }

    override fun initView() {
         super.initView()
        user=findViewById(R.id.user)
        pas=findViewById(R.id.pas)
        register=findViewById(R.id.register)
       register?.setOnClickListener{
          lifecycleScope.launchWhenCreated {
              val u= user?.text.toString()
              val p=pas?.text.toString()
              viewModel.channel.send(UserIntent.Register(p,u))
          }
         }
       lifecycleScope.launch{
           viewModel.observeState.collect {
                  when(it){
                      is UserState.Loading->{
                          Toast.makeText(this@UserActivity, "加载中", Toast.LENGTH_SHORT).show()
                      }
                      is UserState.Success->{
                          Toast.makeText(this@UserActivity, "注册成功:${it.user.username}", Toast.LENGTH_SHORT).show()
                      }
                      is UserState.Failure ->{
                          Toast.makeText(this@UserActivity, it.msg, Toast.LENGTH_SHORT).show()
                      }
                  }
           }
       }
    }
}